package cn.learn.controller;

import cn.learn.domain.ElasticsearchQuery;
import cn.learn.service.IHandlerElasticSearchService;
import cn.learn.service.INsrMapService;
import cn.learn.util.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * es的操作接口
 * 如果前台不传es的index进来，那就从配置文件里面去（配置文件里面的index是默认的）
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2020年06月30日9:10
 */
@RestController
@RequestMapping("/es")
public class ElasticSearchController {

    @Autowired
    private IHandlerElasticSearchService handlerElasticSearchService;
    @Autowired
    private INsrMapService               nsrMapService;

    @Value("${es.index-name}")
    private String index;


    /**
     * 分页查询所有数据
     * ,String topLeft,String bottomRight
     *
     * @param keyword 查询对象
     * @return 所有数据
     */
    @RequestMapping(value = "query", method = RequestMethod.GET)
    public RestResponse queryTop10(String keyword) throws IOException {
        ElasticsearchQuery query = new ElasticsearchQuery();
        query.setColumnName("nsrmc");
        if (query.getIndex() == null) {
            query.setIndex(index);
        }
        query.setKeyword(keyword);
        Map<String, Object> response = handlerElasticSearchService.queryTop10(query);
        return RestResponse.success(response);
    }

    /**
     * 矩形对角的经纬度
     *
     * @param topLeft     左上角（经度，维度）
     * @param bottomRight 右下角（经度，维度）
     * @return 返回结果
     * @throws IOException 流异常
     */
    @RequestMapping(value = "geoBoundingBox", method = RequestMethod.GET)
    public RestResponse geoBoundingBox(String topLeft, String bottomRight) throws IOException {
        ElasticsearchQuery query = new ElasticsearchQuery();
        query.setColumnName("nsrmc");
        if (query.getIndex() == null) {
            query.setIndex(index);
        }
        query.setSize(10000);
        Map<String, Object> response = handlerElasticSearchService.geoBoundingBox(query, topLeft, bottomRight);
        return RestResponse.success(response);
    }

    /**
     * 搜索多边形内的点
     *
     * @param points 坐标点经纬度
     * @return 返回查询结果
     * @throws IOException io流异常
     */
    @RequestMapping(value = "geoPolygon", method = RequestMethod.GET)
    public RestResponse geoPolygon(String[] points) throws IOException {
        long               start = System.currentTimeMillis();
        ElasticsearchQuery query = new ElasticsearchQuery();
        query.setColumnName("nsrmc");
        if (query.getIndex() == null) {
            query.setIndex(index);
        }
        query.setSize(10000);
        Map<String, Object> response = handlerElasticSearchService.geoPolygon(query, points);
        System.out.println(System.currentTimeMillis() - start);
        return RestResponse.success(response);
    }

    /**
     * 执行es数据的写入操作
     *
     * @return 返回保存结果
     * @throws IOException          IO流异常
     * @throws InterruptedException 中断异常，跟线程有关的异常
     */
    @RequestMapping(value = "save", method = RequestMethod.GET)
    public RestResponse save(String indexName) throws IOException, InterruptedException {
        indexName = indexName == null ? index : indexName;
        //每次查询的页码大小是动态的，可更换大小（现在默认1百万）
        int pageSize = 1000000;
        //开始的索引（默认从0开始）
        int pageNum = 0;
        //循环查询数据，写入elasticsearch里面
        List<Map<String, String>> list = null;
        do {
            list = nsrMapService.listPage(pageNum, pageSize);
            handlerElasticSearchService.bulkAsync(indexName, list);
            pageNum++;
        } while (list != null && list.size() >= pageSize);
        return RestResponse.success();
    }

    /**
     * 删除索引
     *
     * @param indexName 索引名称
     * @return 返回结果
     * @throws IOException IO流异常
     */
    @RequestMapping(value = "deleteIndex", method = RequestMethod.GET)
    public RestResponse deleteIndex(String indexName) throws IOException {
        indexName = indexName == null ? index : indexName;
        boolean b = handlerElasticSearchService.deleteIndex(indexName);
        return b ? RestResponse.success() : RestResponse.failed("50001", "删除索引失败");
    }

    /**
     * 创建索引的映射
     *
     * @param indexName 索引名称
     * @param mapping   映射的json文件
     * @return 返回结果
     * @throws IOException IO流异常
     */
    @RequestMapping(value = "createIndexMapping", method = RequestMethod.GET)
    public RestResponse createIndexMapping(String indexName, String mapping) throws IOException {
        indexName = indexName == null ? index : indexName;
        boolean b = handlerElasticSearchService.createIndexMapping(indexName, mapping);
        return b ? RestResponse.success() : RestResponse.failed("50002", "创建索引映射失败");
    }


    /**
     * 政策文档
     *
     * @param index   索引
     * @param keyword 搜索关键词
     * @return 返回结果
     * @throws IOException 流异常
     */
    @RequestMapping(value = "officialDocument", method = RequestMethod.GET)
    public RestResponse officialDocument(String index, String keyword) throws IOException {
        ElasticsearchQuery query = new ElasticsearchQuery();
        query.setIndex(index);
        query.setKeyword(keyword);
        Map<String, Object> response = handlerElasticSearchService.officialDocument(query);
        return RestResponse.success(response);
    }


}
